package com.aivin.lib_base.tool;

import com.aivin.lib_base.bean.CacheSaveBean;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.tencent.mmkv.MMKV;


public class CacheSaveTool {
    private static final int TIME_SECOND = 1;
    private static final int TIME_MINUTES = 60 * TIME_SECOND;
    private static final int TIME_HOUR = 60 * TIME_MINUTES;
    public static final int TIME_DAY = TIME_HOUR * 24;
    private static CacheSaveTool cacheSaveTool = null;

    public static CacheSaveTool getInstance() {
        if (cacheSaveTool == null) {
            cacheSaveTool = new CacheSaveTool();
        }
        return cacheSaveTool;
    }


    public void saveString(String key, String value, int validTime, MMKV mmkv) {
        CacheSaveBean<String> cacheSaveBean = new CacheSaveBean<>(validTime, value, System.currentTimeMillis());
        String beanStr = JSON.toJSONString(cacheSaveBean);
        mmkv.encode(key, beanStr);
    }


    public String getString(String key, MMKV mmkv) {
        String saveValue = mmkv.decodeString(key);
        CacheSaveBean<String> cacheSaveBean = JSON.parseObject(saveValue, new TypeReference<CacheSaveBean<String>>() {
        });

        if (cacheSaveBean == null) {
            return null;
        }

        boolean isTimeOut = isTimeOut(cacheSaveBean);
        return isTimeOut ? null : cacheSaveBean.getValue();
    }


    private boolean isTimeOut(CacheSaveBean bean) {
        return (System.currentTimeMillis() - bean.getSaveTime()) / 1000 > bean.getValidTime();
    }

}